package com.ybox.auth.service.impl;

import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.ybox.auth.domain.Sms;
import com.ybox.auth.service.SendMessageService;
import com.ybox.common.core.constant.CacheConstants;
import com.ybox.common.core.constant.Constants;
import com.ybox.common.core.exception.ServiceException;
import com.ybox.common.core.utils.uuid.IdUtils;
import com.ybox.common.core.web.domain.AjaxResult;
import com.ybox.common.redis.service.RedisService;
import com.ybox.system.api.factory.RemoteLogFallbackFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author 16554
 * @create 2022/7/22 16:27
 * @apiNote
 */
@Service
public class SendMessageServiceImpl implements SendMessageService {

    private static final Logger log = LoggerFactory.getLogger(SendMessageServiceImpl.class);

    @Autowired
    RedisService redisService;

    @Override
    public AjaxResult sendSMSCode(Sms sms) {
        // 生成6位验证码
        long codeL = System.nanoTime();
        String codeStr = Long.toString(codeL);
        String code = codeStr.substring(codeStr.length() - 8, codeStr.length() - 4);
        sms.setCode(code);
        Map<String, Object> voMap = new HashMap<>();
        try {
            String uuid = IdUtils.fastSimpleUUID();
            // 构造存储内容
            voMap.put("phone", sms.getPhone());
            voMap.put("code", sms.getCode());
            // 存储到redis
            String verifyKey = CacheConstants.SMS_CODE_KEY + uuid;
            redisService.setCacheObject(verifyKey, voMap, CacheConstants.SMS_EXPIRATION, TimeUnit.MINUTES);
            // 填充返回结果
            voMap.remove("code");
            voMap.put("uuid", uuid);
            // 发送消息
            sendSms(sms);
        } catch (Exception e) {
            throw new ServiceException("发送失败！请稍后再试！");
        }
        return AjaxResult.success(voMap);
    }


    /**
     * 发送短信
     *
     * @param sms
     */
    @Async
    public void sendSms(Sms sms) {
        String serverIp = "app.cloopen.com";
        // 请求端口
        String serverPort = "8883";
        // 主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
        String accountSId = "8a216da8762cb4570176b8e29a723509";
        String accountToken = "0ea7c8621cf24bbc8bc1999c2f248724";
        // 请使用管理控制台中已创建应用的APPID
        String appId = "8a216da8762cb4570176b8f4924f3516";

        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);


        String[] datas = {sms.getCode(), "5"};
        // String subAppend = "1234";  // 可选 扩展码，四位数字 0~9999
        // String reqId = "fadfafas";  // 可选 第三方自定义消息id，最大支持32位英文数字，同账号下同一自然天内不允许重复


        HashMap<String, Object> result = sdk.sendTemplateSMS(sms.getPhone(),"1",datas);
        // HashMap<String, Object> result = sdk.sendTemplateSMS(sms.getPhone(), "1", datas, subAppend, reqId);
        if ("000000".equals(result.get("statusCode"))) {
            // 正常返回输出data包体信息（map）
            HashMap<String, Object> data = (HashMap<String, Object>) result.get("data");
            Set<String> keySet = data.keySet();
            for (String key : keySet) {
                Object object = data.get(key);
                log.info(key + " = " + object);
            }
        } else {
            // 异常返回输出错误码和错误信息
            log.error("错误码=" + result.get("statusCode") + " 错误信息= " + result.get("statusMsg"));
        }
    }

}
